import * as types from "../action-types";
import { AnyAction } from "redux";
import * as homeAPI from "@/api/home";
import { message } from "antd";

export function setCurrentCategory(category: string): AnyAction {
  return {
    type: types.SET_CURRENT_CATEGORY,
    payload: category,
  };
}

export function getSliders(): AnyAction {
  return {
    type: types.GET_SLIDERS,
    payload: homeAPI.getSliders(),
  };
}

export function getDogs() {
  return (dispatch: any, getState: any) => {
    (async function () {
      let {
        currentCategory,
        dogs: { hasMore, offset, limit, loading },
      } = getState().home;
      if (hasMore && !loading) {
        dispatch({
          type: types.SET_DOGS_LOADING,
          payload: true,
        });
        try {
          let result = await homeAPI.getDogs(currentCategory, offset, limit);
          dispatch({ type: types.SET_DOGS, payload: result.data });
        } catch (e) {
          message.error(e.message);
        }
      }
    })();
  };
}

export function refreshDogs() {
  return (dispatch: any, getState: any) => {
    (async function () {
      let {
        currentCategory,
        dogs: { limit, loading },
      } = getState().home;
      if (!loading) {
        dispatch({
          type: types.SET_DOGS_LOADING,
          payload: true,
        });
        try {
          let result = await homeAPI.getDogs(currentCategory, 0, limit);
          dispatch({
            type: types.REFRESH_DOGS,
            payload: result.data,
          });
        } catch (e) {
          message.error(e.message);
        }
      }
    })();
  };
}
